import { toolchain } from "../../toolchain.js";
import { BaseTask, TaskResult } from "./BastTask.js";
import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { EFileErrorType, alertErrorFile, sendBuildFailureAlert } from "../../tools/alert.js";

export class CheckCodeTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        // 检查ts代码中是否含有import csharp
        const tsRoot = path.join(toolchain.params.workSpacePath, 'TsScripts');
        const tsFiles = await fg('**/*.ts', { cwd: tsRoot });
        const errorFiles: string[] = [];
        for (const tsf of tsFiles) {
            const file = path.join(tsRoot, tsf);
            const content = await fs.readFile(file, 'utf-8');
            if (content.search(/import .+ from (['"]{1})csharp\1/) >= 0) {
                errorFiles.push(tsf);
            }
        }
        if (errorFiles.length > 0) {
            const msg = '不允许直接import csharp: \n' + errorFiles.join('\n');
            await alertErrorFile(errorFiles[0], EFileErrorType.CodeError, msg);
            await sendBuildFailureAlert(msg);
            process.exit(1);
        }

        return { success: true, errorCode: 0 };
    }
}
